package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;


    /**
     * 根据id删除分类信息
     * @param categoryId
     */
    public void remove(Long categoryId){
        //1. 根据分类id查询菜品信息
        LambdaQueryWrapper<Dish> dishWrapper = new LambdaQueryWrapper();
        dishWrapper.eq(Dish::getCategoryId,categoryId);
        int dishCount = dishService.count(dishWrapper);

        //2. 如果有当前分类关联的菜品信息,则不能删除当前分类
        if (dishCount > 0){
            throw new CustomException("当前分类下有相关菜品数据,不能删除!");
        }

        //3. 根据分类id查询套餐信息
        LambdaQueryWrapper<Setmeal> mealWrapper = new LambdaQueryWrapper();
        mealWrapper.eq(Setmeal::getCategoryId,categoryId);
        int mealCount = setmealService.count(mealWrapper);

        //4. 如果有当前分类关联的套餐信息,则不能删除当前分类
        if (mealCount > 0){
            throw new CustomException("当前分类下有相关套餐数据,不能删除!");
        }

        //没有关联数据,则根据id删除
        this.removeById(categoryId);
    }
}
